    // 全局变量
    let checkAll = false // 全选默认状态设置
    const tableEle = document.querySelector('#cart table') //列表容器
    
    
    //渲染用户信息
      function showUser() {
          let userstr = localStorage.getItem('USER')
          let user = JSON.parse(userstr) || []
          if (user == '') {
              return
          }
          const box = document.querySelector('#header .user')
          box.innerHTML = `<span>您好~${user.username}</span>`
      }
      
     /* 
     *动态渲染购物车
     */
    
     function showCart(){
         //从localstorage中获取购物车商品数据
         let productListStr = localStorage.getItem('XIAOMI_CART')
         let productList = JSON.parse(productListStr)
         let thStr = `   <tr>
                            <th><input type="checkbox" name="checkAll" ${checkAll?'checked':''}>&emsp;全选</th>
                            <th>商品名称</th>
                            <th>单价</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>操作</th>
                        </tr>`
         let str = productList.map(item => {
             return `   <tr>
                        <td><input type="checkbox" name="checkSingle" data-index="${item.id}" ${item.state?'checked':''}>&emsp;</td>
                        <td><h1><a href="../pages/details.html?id=${item.id}"><img src="${item.url}" alt="${item.name}"><span>${item.name}</span></a></h1></td>
                        <td>${item.price}元</td>
                        <td><button type="button" name="minus" data-index="${item.id}" ${item.num<=1?'disabled':''}>-</button><input type="text" name="amount" value="${item.num}" data-index="${item.id}"><button type="button" name="plus" data-index="${item.id}">+</button></td>
                        <td>${(item.price * item.num).toFixed(2)}元</td>
                        <td><a class="del" data-index="${item.id}">x</a ></td>
                    </tr>`
         }).join('')
         thStr +=  str 
         tableEle.innerHTML = thStr
         productNum()
         tip()
     }
     /* 
 * 商品操作功能  -增删查改
 */
function onProducList() {
    tableEle.addEventListener('click', function (e) { //利用事件冒泡绑定点击事件
        e = e || window.event //事件对象
        let target = e.tatget || e.srcElement //事件目标对象
        //获取locaStorage商品数组数据
        let productListStr = localStorage.getItem('XIAOMI_CART')
        let productList = JSON.parse(productListStr)
        /* 
         * 1.商品全选功能
         */
        if (target.getAttribute('name') == 'checkAll') {
            checkAll = !checkAll // 1.1点击全选按钮全选状态改变 
            productList.forEach(item => item.state = checkAll) //1.2判断全选状态，如果为true，遍历所有单选按钮，将他们的状态改为true,同理改变为false
            localStorage.setItem('XIAOMI_CART', JSON.stringify(productList)) //1.3持久化存储商品对象到locaStorage  
            onTotalPrice()   //1.4计算商品总价
            showCart() //1.5重新渲染页面
        }
        /* 
         * 2.商品单选功能
         */
        if (target.getAttribute('name') == 'checkSingle') {
            let id = target.getAttribute('data-index') //2.1获取商品id
            let product = productList.find(item => item.id == id) //根据id号从数组中取出该商品
            product.state = !product.state //2.3该商品选中状态改变
            checkAll = productList.every(item => item.state == true) //2.4判断所有单选按钮状态，都被选中全选按钮为true，如果有一个未被选中，全选按钮为false
            localStorage.setItem('XIAOMI_CART', JSON.stringify(productList)) //2.5持久化存储商品对象到localStorage
            onTotalPrice()  //2.6计算商品总价
            showCart() //2.7重新渲染页面
        }
        /* 
         * 3.商品数量增加
         */
        if (target.getAttribute('name') == 'plus') {
            let id = target.getAttribute('data-index') //3.1获取操作商品id
            let product = productList.find(item => item.id == id) //3.2根据商品id从商品数组中取出该商品
            product.num++ //3.3商品数量增加
            product.singlePrice = (product.num * product.price).toFixed(2) //3.4商品价格等于单价乘以数量
            product.state = true //3.5选中该商品
            localStorage.setItem('XIAOMI_CART', JSON.stringify(productList)) //3.6持久化存储商品对象
            onTotalPrice() //3.7计算商品总价
            showCart() //3.8重新渲染页面
        }
        /* 
         * 4.商品数量减少
         */
        if (target.getAttribute('name') == 'minus') {
            let id = target.getAttribute('data-index') //4.1获取操作商品id
            let product = productList.find(item => item.id == id) //4.2根据商品id从商品数组中取出该商品
            product.num-- //4.3商品数量减少
            product.singlePrice = (product.num * product.price).toFixed(2) //4.4商品价格等于单价乘以数量
            product.state = true //4.5选中该商品
            localStorage.setItem('XIAOMI_CART', JSON.stringify(productList)) //4.6持久化存储商品对象
            onTotalPrice() //4.7计算商品总价
            showCart() //4.8重新渲染页面 
        }
        /* 
         * 5.删除该商品
         */
        if (target.getAttribute('class') == 'del') {
            let id = target.getAttribute('data-index') //5.1获取操作商品id
            let index = productList.findIndex(item => item.id == id) //5.2根据商品id返回商品数组中该商品的索引号
            productList.splice(index, 1) //5.3根据索引号删除该商品
            localStorage.setItem('XIAOMI_CART', JSON.stringify(productList)) //5.4持久化存储商品对象
            onTotalPrice() //5.5计算商品总价
            showCart()//5.6重新渲染页面 
        }
        
    })
}
/* 
 * 计算所有商品总价
 */
function onTotalPrice() {
    //获取locaStorage商品数组数据
    let productListStr = localStorage.getItem('XIAOMI_CART')
    let productList = JSON.parse(productListStr)
    //获取总价元素
    let totalPriceEle = document.querySelector('.totalPrice>span') 
    //获取所有被选中的商品
    let newProductList =productList.filter(item => item.state == true) 
    console.log(newProductList,'newProductList');
    // 累加所有被选中商品的价格得到总价格
    let totalPrice = 0
    for (let i = 0; i < newProductList.length; i++) {
       totalPrice +=  Number( newProductList[i].singlePrice)
    }
    // let totalPrice = newProductList.reduce((previous, current) => {
    //     previous + Number(current.singlePrice)
    //     console.log(totalPrice,'totalPrice',current.singlePrice,'current.singlePrice');
    // }, 0) 
    // console.log(totalPrice,'totalPrice');
    // //拼接字符串输出总价
    totalPriceEle.innerHTML = totalPrice.toFixed(2) 
}


/* 
* 恢复选择按钮初始状态
*/
function restoreCheckbox(){
    //从localStorage中拿到商品数组
    let productListStr = localStorage.getItem("XIAOMI_CART")
    let productList = JSON.parse(productListStr) || []
    //将所有商品的单选框恢复初始状态
    productList.forEach(item => item.state = false)
    //将全选按钮选框恢复初始状态
    checkAll = false
    //持久化存储商品对象
    localStorage.setItem('XIAOMI_CART',JSON.stringify(productList))
    showCart() //重新渲染页面
}

// 显示购物车已选择数量
function productNum(){
    const amountEle = document.querySelector('#cart .amount')
    //从localStorage中拿到商品数组
    let productListStr = localStorage.getItem("XIAOMI_CART")
    let productList = JSON.parse(productListStr) || []
    let amount = 0
      productList.forEach(item =>{
        if( item.state == true){
            amount++
        }
    })
    amountEle.innerHTML = amount
    
}
/* 
数量减少按钮禁用的时候，鼠标样式改变为禁用
*/
function tip(){
    let minusEles = document.querySelectorAll('#cart table button[name = minus]')
    let amountEles = document.querySelectorAll('#cart table input[name = amount]')
    for (let i = 0; i < minusEles.length; i++) {
       if (amountEles[i].value == 1) {
        minusEles[i].classList.add('disabled')
       } 
    }
}

onProducList()
showUser()
restoreCheckbox()